package com.huhao.smark;

import static android.content.Context.MODE_PRIVATE;
import static com.huhao.smark.Config.BASE_URL;
import static com.huhao.smark.Config.ADD_RECORD;
import static com.huhao.smark.Config.NEWS_API;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment implements SharedPreferences.OnSharedPreferenceChangeListener {

    private static final String TAG = "HomeFragment";
    private ActivityResultLauncher<Intent> activityLauncher;
    private RecyclerView newsRecyclerView;
    private TextView dateTextView;
    private TextView microWordTextView;
    private TextView tvTodayExpense;
    private TextView tvExpenseTip;
    private NewsAdapter newsAdapter;
    private OkHttpClient client;
    private List<NewsItem> newsList = new ArrayList<>();
    private SharedPreferences sharedPreferences;
    private boolean isLoggedIn = false;
    private final DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        Button search = view.findViewById(R.id.search_button);

        // 设置点击监听器，启动搜索界面
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SearchActivity.class);
                startActivity(intent);
            }
        });

        // 初始化今日消费区块和登录提示区块
        FrameLayout todayExpenseBlock = view.findViewById(R.id.today_expense_block);
        FrameLayout loginReminderBlock = view.findViewById(R.id.login_reminder_block);

        // 从 SharedPreferences 中读取登录状态
        sharedPreferences = requireActivity().getSharedPreferences("app_prefs", MODE_PRIVATE);
        isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

        // 注册 SharedPreferences 监听器
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);

        // 初始化金额和提示视图
        tvTodayExpense = todayExpenseBlock.findViewById(R.id.tv_today_expense_amount);
        tvExpenseTip = todayExpenseBlock.findViewById(R.id.tv_expense_tip);

        // 根据登录状态设置区块的可见性
        if (isLoggedIn) {
            todayExpenseBlock.setVisibility(View.VISIBLE);
            loginReminderBlock.setVisibility(View.GONE);
        } else {
            todayExpenseBlock.setVisibility(View.GONE);
            loginReminderBlock.setVisibility(View.VISIBLE);
        }

        // 为登录按钮添加点击事件
        Button loginButton = loginReminderBlock.findViewById(R.id.login_button);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到登录页面或处理登录逻辑
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            }
        });

        // 为今日花钱的区域添加点击事件
        todayExpenseBlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewPager2 viewPager = ((MainActivity) requireActivity()).findViewById(R.id.view_pager2);
                viewPager.setCurrentItem(1);
            }
        });

        // 初始化新闻列表
        newsRecyclerView = view.findViewById(R.id.news_recycler_view);
        dateTextView = view.findViewById(R.id.date_text_view);
        microWordTextView = view.findViewById(R.id.micro_word_text_view);
        newsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        newsAdapter = new NewsAdapter(newsList);
        newsRecyclerView.setAdapter(newsAdapter);
        client = new OkHttpClient();

        // 获取新闻数据
        fetchNewsData();

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 如果已登录，加载今日开销
        if (isLoggedIn) {
            loadTodayExpense();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次进入页面刷新数据
        if (isLoggedIn) {
            loadTodayExpense();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (sharedPreferences != null) {
            sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("isLoggedIn")) {
            isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
            updateUIBasedOnLoginStatus();
            if (isLoggedIn) {
                loadTodayExpense(); // 登录状态变化时刷新
            }
        }
    }

    private void updateUIBasedOnLoginStatus() {
        View view = getView();
        if (view == null) return;

        FrameLayout todayExpenseBlock = view.findViewById(R.id.today_expense_block);
        FrameLayout loginReminderBlock = view.findViewById(R.id.login_reminder_block);

        if (isLoggedIn) {
            todayExpenseBlock.setVisibility(View.VISIBLE);
            loginReminderBlock.setVisibility(View.GONE);
        } else {
            todayExpenseBlock.setVisibility(View.GONE);
            loginReminderBlock.setVisibility(View.VISIBLE);
        }
    }

    private void loadTodayExpense() {
        SharedPreferences prefs = requireActivity().getSharedPreferences("app_prefs", MODE_PRIVATE);
        String token = prefs.getString("token", "");

        if (token.isEmpty()) {
            Log.d(TAG, "Token is empty, cannot load today's expense");
            return;
        }

        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String today = String.format(Locale.getDefault(), "%d-%02d-%02d", year, month, day);

        String url = BASE_URL + ADD_RECORD +
                "?year=" + year +
                "&month=" + month;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "加载今日开销失败: " + e.getMessage());
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "获取今日开销失败，请检查网络", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    try {
                        JSONObject json = new JSONObject(responseData);
                        if (json.getBoolean("success")) {
                            JSONArray data = json.getJSONArray("data");
                            double totalExpense = 0.0;

                            // 筛选今天的支出记录
                            for (int i = 0; i < data.length(); i++) {
                                JSONObject item = data.getJSONObject(i);
                                String recordDate = item.getString("bookDate");
                                int type = item.getInt("type");

                                // 检查日期是否匹配且类型为支出
                                if (recordDate.equals(today) && type == 1) {
                                    totalExpense += item.getDouble("price");
                                }
                            }

                            // 更新UI
                            double finalTotalExpense = totalExpense;
                            requireActivity().runOnUiThread(() -> {
                                tvTodayExpense.setText(decimalFormat.format(finalTotalExpense) + "元");
                                // 根据金额显示不同提示
                                if (finalTotalExpense > 500) {
                                    tvExpenseTip.setText("消费较高，注意节制！");
                                } else if (finalTotalExpense > 200) {
                                    tvExpenseTip.setText("理性消费哦~");
                                } else if (finalTotalExpense > 0) {
                                    tvExpenseTip.setText("继续保持！");
                                } else {
                                    tvExpenseTip.setText("今日暂无消费");
                                }
                            });
                        } else {
                            Log.e(TAG, "获取数据失败: " + json.getString("message"));
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "解析数据错误: " + e.getMessage());
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "解析数据失败", Toast.LENGTH_SHORT).show();
                        });
                    }
                } else {
                    Log.e(TAG, "请求失败，状态码: " + response.code());
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "获取数据失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private void fetchNewsData() {
        Request request = new Request.Builder()
                .url(NEWS_API)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "获取新闻失败，请检查网络连接。", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String newsContent = response.body().string();
                    requireActivity().runOnUiThread(() -> {
                        processNewsContent(newsContent);
                    });
                } else {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "获取新闻失败，服务端错误。", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private void processNewsContent(String newsContent) {
        String[] lines = newsContent.split("\n");
        if (lines.length > 0) {
            String title = lines[0];
            dateTextView.setText(title);
            for (int i = 1; i < lines.length; i++) {
                String line = lines[i];
                if (!line.isEmpty() && !line.startsWith("【微语】")) {
                    newsList.add(new NewsItem(line));
                } else if (line.startsWith("【微语】")) {
                    microWordTextView.setText(line.replace("【微语】", ""));
                    microWordTextView.setVisibility(View.VISIBLE);
                }
            }
            newsAdapter.notifyDataSetChanged();
        }
    }

    private static class NewsItem {
        private String content;

        public NewsItem(String content) {
            this.content = content;
        }

        public String getContent() {
            return content;
        }
    }

    private static class NewsViewHolder extends RecyclerView.ViewHolder {
        private TextView newsContent;

        public NewsViewHolder(View itemView) {
            super(itemView);
            newsContent = itemView.findViewById(R.id.news_content);
        }

        public void bind(NewsItem newsItem) {
            newsContent.setText(newsItem.getContent());
        }
    }

    private static class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> {
        private final List<NewsItem> newsList;

        public NewsAdapter(List<NewsItem> newsList) {
            this.newsList = newsList;
        }

        @Override
        public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.news_item, parent, false);
            return new NewsViewHolder(view);
        }

        @Override
        public void onBindViewHolder(NewsViewHolder holder, int position) {
            holder.bind(newsList.get(position));
        }

        @Override
        public int getItemCount() {
            return newsList.size();
        }
    }
}